package com.csdn.leon.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.csdn.leon.model.BlogModel;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.model.ClumnsHost;
import com.csdn.leon.model.Person;

import android.text.TextUtils;
import android.util.Log;



public class JsoupUtil {

	public static Person getPersonInfo(String str) {
		if (str == null) {
			return null;
		}
		Document doc = Jsoup.parse(str);
		Element profile = doc.getElementsByClass("panel").get(0);

		Element profileBody = profile.select("ul.panel_body.profile").get(0);

		Element userface = profileBody.getElementById("blog_userface");
		String userfaceLink = userface.select("a").select("img").attr("src"); // 得到头像链接
		String username = userface.getElementsByTag("a").get(1).text(); // 用户名

		Element blog_rank = profileBody.getElementById("blog_rank");

		Element blog_statistics = profileBody.getElementById("blog_statistics");

		Elements rankLi = blog_rank.select("li");
		String gradeLink = rankLi.select("li").select("img").attr("src");
		System.out.println("等级路径===" + gradeLink);
		StringBuilder sb = new StringBuilder();
		String rankStr = "";

		for (int i = 0; i < rankLi.size(); i++) {

			if (i == 2) {
				sb.append("");
			} else {
				sb.append(rankLi.get(i).text()).append("|");
			}
		}
		rankStr = sb.substring(0, sb.lastIndexOf("|")).toString();

		// Log.e("rankStr", rankStr);
		String statistics = "";
		StringBuilder sb2 = new StringBuilder();
		Elements blogLi = blog_statistics.select("li");
		for (int i = 0; i < blogLi.size(); i++) {
			Log.e("ranklllll", blogLi.get(i) + "");

			sb2.append(blogLi.get(i).text()).append(" | ");

		}
		statistics = sb2.substring(0, sb2.lastIndexOf("|")).toString();
		// Log.e("statistics", statistics);
		Person person = new Person();
		person.setUserface(userfaceLink);
		person.setRank(gradeLink);

		System.out.println("头像路径===" + userfaceLink);
		person.setUsername(username);
		person.setRank(rankStr);
		person.setStatistics(statistics);
		return person;

	}

	/**
	 * 扒取传入url地址的博客详细内容
	 * 
	 * @param url
	 * @param str
	 * @return
	 */
	public static List<BlogModel> getContent(String str) {

		List<BlogModel> list = new ArrayList<BlogModel>();
		// 获取文档内容
		Document doc = Jsoup.parse(str);

		// 获取class="details"的元素
		Element detail = doc.getElementsByClass("details").get(0);
		detail.select("script").remove(); // 删除每个匹配元素的DOM。
		String blog_time = detail.getElementsByClass("link_postdate").text()
				+ "  " + detail.getElementsByClass("link_view").text();

		// 获取标题
		Element title = detail.getElementsByClass("article_title").get(0);
		BlogModel blogTitle = new BlogModel();
		System.out.println("设置文章的标题：" + ToDBC(title.text()));
		blogTitle.setState(Constants.DEF_BLOG_ITEM_TYPE.TITLE); // 设置状态
		blogTitle.setContent(ToDBC(title.text())); // 设置标题内容
		blogTitle.setDate(blog_time);
		list.add(blogTitle);
		// 获取文章内容
		Element content = detail.select("div.article_content").get(0);

		// 获取所有标签为<a的元素
		Elements as = detail.getElementsByTag("a");
		for (int b = 0; b < as.size(); b++) {
			Element blockquote = as.get(b);
			// 改变这个元素的标记。例如,<span>转换为<div> 如el.tagName("div");。
			blockquote.tagName("bold"); // 转为粗体
		}

		Elements ss = detail.getElementsByTag("strong");
		for (int b = 0; b < ss.size(); b++) {
			Element blockquote = ss.get(b);
			blockquote.tagName("bold");
		}

		// 获取所有标签为<p的元素
		Elements ps = detail.getElementsByTag("p");
		for (int b = 0; b < ps.size(); b++) {
			Element blockquote = ps.get(b);
			blockquote.tagName("body");
		}

		// 获取所有引用元素
		Elements blockquotes = detail.getElementsByTag("blockquote");
		for (int b = 0; b < blockquotes.size(); b++) {
			Element blockquote = blockquotes.get(b);
			blockquote.tagName("body");
		}

		// 获取所有标签为<ul的元素
		Elements uls = detail.getElementsByTag("ul");
		for (int b = 0; b < uls.size(); b++) {
			Element blockquote = uls.get(b);
			blockquote.tagName("body");
		}

		// 找出粗体
		Elements bs = detail.getElementsByTag("b");
		for (int b = 0; b < bs.size(); b++) {
			Element bold = bs.get(b);
			bold.tagName("bold");
		}

		// 遍历博客内容中的所有元素
		for (int j = 0; j < content.children().size(); j++) {
			Element c = content.child(j); // 获取每个元素

			// 抽取出图片
			if (c.select("img").size() > 0) {
				Elements imgs = c.getElementsByTag("img");
				System.out.println("img");
				for (Element img : imgs) {
					if (!img.attr("src").equals("")) {
						BlogModel blogImgs = new BlogModel();
						// 大图链接
						if (!img.parent().attr("href").equals("")) {
							blogImgs.setImgLink(img.parent().attr("href"));
							System.out.println("href="
									+ img.parent().attr("href"));
							if (img.parent().parent().tagName().equals("p")) {
								// img.parent().parent().remove();
							}
							img.parent().remove();
						}
						blogImgs.setContent(img.attr("src"));
						blogImgs.setImgLink(img.attr("src"));
						System.out.println(blogImgs.getContent());
						blogImgs.setState(Constants.DEF_BLOG_ITEM_TYPE.IMG);
						list.add(blogImgs);
					}
				}
			}
			c.select("img").remove();

			// 获取博客内容
			BlogModel blogContent = new BlogModel();
			blogContent.setState(Constants.DEF_BLOG_ITEM_TYPE.CONTENT);

			if (c.text().equals("")) {
				continue;
			} else if (c.children().size() == 1) {
				if (c.child(0).tagName().equals("bold")
						|| c.child(0).tagName().equals("span")) {
					if (c.ownText().equals("")) {
						// 小标题，咖啡色
						blogContent
								.setState(Constants.DEF_BLOG_ITEM_TYPE.BOLD_TITLE);
					}
				}
			}

			// 代码
			if (c.select("pre").attr("name").equals("code")) {
				blogContent.setState(Constants.DEF_BLOG_ITEM_TYPE.CODE);
				blogContent.setContent(ToDBC(c.outerHtml()));
			} else {
				blogContent.setContent(ToDBC(c.outerHtml()));
			}
			// System.out.println("blogcontent_cc"+blogContent);
			list.add(blogContent);
		}

		return list;
	}
	/**
	 * 获取博客详情内容
	 * 
	 * @param paramString
	 * @return
	 */
	public static String getContentHtml(String paramString) {
		if (TextUtils.isEmpty(paramString)) {
			return null;
		}

		Element localElement1 = Jsoup.parse(paramString).getElementsByClass("details").get(0);

		// 获取详情
		localElement1.select("script").remove();
		if (localElement1.getElementById("digg") != null) {
			localElement1.getElementById("digg").remove();
		}
		if (localElement1.getElementsByClass("tag2box") != null) {
			localElement1.getElementsByClass("tag2box").remove();
		}
		localElement1.getElementsByClass("article_manage").remove();
		localElement1.getElementsByTag("h1").tagName("h2");
		Iterator<?> localIterator = localElement1.select("pre[name=code]").iterator();
		while (true) {
			if (!localIterator.hasNext())
				return localElement1.toString();
			Element localElement2 = (Element) localIterator.next();
			localElement2.attr("class", "brush: java; gutter: false;");
			Log.i("CSNDBlog_JsoupUtil", "codeNode.text()" + localElement2.text());
		}
	}

//	public static List<Comment> getCommentList(String str, int pageIndex,
//			int pageSize) {
//		List<Comment> list = new ArrayList<Comment>();
//
//		try {
//			JSONObject jsonobject = new JSONObject(str);
//			JSONArray arry = jsonobject.getJSONArray("list");
//			int index = 0;
//			int len = arry.length();
//			BlogCommentActivity.commentCount = String.valueOf(len);
//
//			// 如果评论数大于20
//			if (len > 20) {
//				index = (pageIndex * pageSize) - 20;
//			}
//
//			if (len < pageSize && pageIndex > 1) {
//				return list;
//			}
//
//			if ((pageIndex * pageSize) < len) {
//				len = pageIndex * pageSize;
//			}
//
//			for (int i = index; i < len; i++) {
//				JSONObject item = arry.getJSONObject(i);
//				String commentId = item.getString("CommentId");
//				String content = item.getString("Content");
//				String username = item.getString("UserName");
//				String parentId = item.getString("ParentId");
//				String postTime = item.getString("PostTime");
//				String userface = item.getString("Userface");
//
////				System.out.println("commentid==" + commentId + "  content==="
////						+ content + "  username===" + username
////						+ "  parentId===" + parentId + "  postTime==="
////						+ postTime + "  userface" + userface);
//
//				Comment comment = new Comment();
//				comment.setCommentId(commentId);
//				comment.setContent(content);
//				comment.setUsername(username);
//				comment.setParentId(parentId);
//				comment.setPostTime(postTime);
//				comment.setUserface(userface);
//
//				if (parentId.equals("0")) {
//					// 如果parentId为0的话，表示它是评论的topic
//					comment.setType(Constants.DEF_COMMENT_TYPE.PARENT);
//				} else {
//					comment.setType(Constants.DEF_COMMENT_TYPE.CHILD);
//				}
//				list.add(comment);
//			}
//
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		return list;
//	}

	public static List<BlogModel> getFirstBlogItemList(int bolgType, String str) {

		List<BlogModel> list = new ArrayList<BlogModel>();
		Document doc = Jsoup.parse(str);

		String pages = doc.getElementsByClass("page_nav").select("span").text();
		// System.out.println("pages"+pages);
		String totals = pages.substring(0, pages.indexOf(" "));
		int total = getPageNo(pages.substring(0, pages.indexOf(" ")));
		int pageSize = getPageNo(pages.substring(pages.indexOf(" "),
				pages.length()));

		Elements bloglist = doc.getElementsByClass("blog_list");
		for (Element blogitem : bloglist) {
			BlogModel item = new BlogModel();
			String title = blogitem.select("h1").text();
			String link = blogitem.select("h1").select("a").attr("href");
			String id = blogitem.select("h1").select("a").attr("name");
			String imageLink = blogitem.select("dt").select("img").attr("src");
			String detail = blogitem.select("dd").text();
			String username = blogitem.getElementsByClass("user_name").text();
			String date = blogitem.getElementsByClass("time").text();
			String totalread = blogitem.getElementsByClass("view").text();
			String totalComment = blogitem.getElementsByClass("comment").text();
			item.setTitle(title);
			item.setContent(detail);
			item.setLink(link);
			item.setId(id);
			item.setType(bolgType);
			item.setDate(date);
			item.setImgLink(imageLink);
			item.setUsername(username);
			item.setTotalread(totalread);
			item.setTotalcomment(totalComment);
			list.add(item);
		}

		return list;
	}

//	public static Map<List<BlogItem>, Integer> getBlogItemList(int bolgType,
//			String str) {
//		Map<List<BlogItem>, Integer> map = new HashMap<List<BlogItem>, Integer>();
//
//		List<BlogItem> list = new ArrayList<BlogItem>();
//		Document doc = Jsoup.parse(str);
//
//		String pages = doc.getElementsByClass("page_nav").select("span").text();
//		// System.out.println("pages"+pages);
//		String totals = pages.substring(0, pages.indexOf(" "));
//		int total = getPageNo(pages.substring(0, pages.indexOf(" ")));
//		int pageSize = getPageNo(pages.substring(pages.indexOf(" "),
//				pages.length()));
//
//		Elements bloglist = doc.getElementsByClass("blog_list");
//		for (Element blogitem : bloglist) {
//			BlogItem item = new BlogItem();
//			String title = blogitem.select("h1").text();
//			String link = blogitem.select("h1").select("a").attr("href");
//			String id = blogitem.select("h1").select("a").attr("name");
//			String imageLink = blogitem.select("dt").select("img").attr("src");
//			String detail = blogitem.select("dd").text();
//			String username = blogitem.getElementsByClass("user_name").text();
//			String date = blogitem.getElementsByClass("time").text();
//			String totalread = blogitem.getElementsByClass("view").text();
//			String totalComment = blogitem.getElementsByClass("comment").text();
//			System.out.println("totalread==" + totalread + "  totalComment"
//					+ totalComment);
//
//			item.setTitle(title);
//			item.setContent(detail);
//			item.setLink(link);
//			item.setId(id);
//			item.setType(bolgType);
//			item.setDate(date);
//			item.setImgLink(imageLink);
//			item.setUsername(username);
//			item.setTotalread(totalread);
//			item.setTotalcomment(totalComment);
//			list.add(item);
//		}
//		map.put(list, pageSize);
//		return map;
//	}
//
	/*
	 * 获取博主所有的博文
	 */

	public static Map<String, Object> getHostBlogList(String temp) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<BlogModel> list = new ArrayList<BlogModel>();
		Person person = getPersonInfo(temp);
		map.put("person", person);
		Document doc = Jsoup.parse(temp);
		Elements bloglist = doc.getElementsByClass("list_item");
		for (Element blogItem : bloglist) {
			BlogModel item = new BlogModel();
			String title = blogItem.select("h1").text();
			String link = blogItem.select("h1").select("a").attr("href");
			String content = blogItem.getElementsByClass("article_description")
					.text();
			String date = blogItem.getElementsByClass("article_manage").text();
			// item.setTitle(blogItem.get)
			item.setTitle(title);
			item.setLink(link);
			item.setContent(content);
			item.setDate(date);
			list.add(item);
		}
		map.put("list", list);
		return map;
	}
//
//	public static List<GridBlogItem> getAllCloumnList(String httpTemp) {
//		List<GridBlogItem> headList = new ArrayList<GridBlogItem>();
//		Document doc = Jsoup.parse(httpTemp);
//		Elements gridList = doc.getElementsByClass("columns_recom")
//				.select("dl");
//		for (Element item : gridList) {
//			GridBlogItem gridItem = new GridBlogItem();
//			String title = item.select("dd").select("a").text();
//			String content = item.select("dd").text();
//			// Log.e("GRIDVIEW===", title+"  "+content);
//			String link = item.select("dt").select("a").attr("href");
//			String imageLink = item.select("dt").select("img").attr("src");
//			String username = item.select("dt").text();
//			gridItem.setTitle(title);
//			gridItem.setLink("http://blog.csdn.net/" + link);
//			gridItem.setImageLink(imageLink);
//			gridItem.setUsername(username);
//			gridItem.setContent(content);
//			headList.add(gridItem);
//		}
//		return headList;
//	}
//
	// 获取推介专栏
	public static List<CloumnModel> getClumnsBlogList(String httpTemp) {
		Map<String, List> map = new HashMap<String, List>();
		List<CloumnModel> list = new ArrayList<CloumnModel>();
		//List<GridBlogItem> headList = new ArrayList<GridBlogItem>();
		Document doc = Jsoup.parse(httpTemp);
		Elements gridList = doc.getElementsByClass("columns_recom")
				.select("dl");
//		for (Element item : gridList) {
//			GridBlogItem gridItem = new GridBlogItem();
//			String title = item.select("dd").select("a").text();
//			String content = item.select("dd").text();
//			// Log.e("GRIDVIEW===", title+"  "+content);
//			String link = item.select("dt").select("a").attr("href");
//			String imageLink = item.select("dt").select("img").attr("src");
//			String username = item.select("dt").text();
//			gridItem.setTitle(title);
//			gridItem.setLink("http://blog.csdn.net/" + link);
//			gridItem.setImageLink(imageLink);
//			gridItem.setUsername(username);
//			gridItem.setContent(content);
//			headList.add(gridItem);
//		}
//		map.put("headList", headList);
		Elements bloglist = doc.getElementsByClass("blog_list");
		for (Element item : bloglist) {
			CloumnModel clumnsBlogItem = new CloumnModel();
			String title = item.select("h1").text();
			String link = item.getElementsByClass("about_info").select("span")
					.select("a").last().attr("href");
			// System.out.println("************************");
			// System.out.println(link);
			// System.out.println("************************");
			String imageLink = item.select("dt").select("img").attr("src");
			String username = item.select("dt").select("img").attr("alt");
			String content = item.select("dd").text();
			String clumnsLink = item.getElementsByClass("column").select("a")
					.attr("href");
			String clumnName = item.getElementsByClass("column").text();
			String date = item.getElementsByClass("time").text();

			clumnsBlogItem.setTitle(title);
			clumnsBlogItem.setClumnName(clumnName);
			clumnsBlogItem.setContent(content);
			clumnsBlogItem.setDate(date);
			clumnsBlogItem.setImageLink(imageLink);
			clumnsBlogItem.setLink(link);
			clumnsBlogItem.setTitle(title);
			clumnsBlogItem.setUsername(username);
			clumnsBlogItem.setClumnLink("http://blog.csdn.net" + clumnsLink);
			// System.out.println("clumnsBlogItem=="+clumnsBlogItem.toString());
			list.add(clumnsBlogItem);
		}
		//map.put("list", list);
		return list;

	}

	// 获取专栏列表
	public static Map<String,Object> getCloumnsList(String temp) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CloumnModel> list = new ArrayList<CloumnModel>();
		//List<CloumnTag> taglist = null;
		ClumnsHost host = new ClumnsHost();

		Document doc = Jsoup.parse(temp);
		Elements hostElement = doc.getElementsByClass("columns_detailed");
		String clumntitle = hostElement.get(0).getElementsByClass("title")
				.text();
		String clumnImageUrl = hostElement.select("dt").select("img")
				.attr("src");
		String clumnContent = hostElement.get(0).getElementById("col_desc")
				.text();

		host.setClumnName(clumntitle);
		host.setClumnImageUrl(clumnImageUrl);
		host.setClumnContent(clumnContent);
		System.out.println("jsouputil===" + host.getClumnName()
				+ host.getClumnContent());
		map.put("host", host);
		Elements bloglist = doc.getElementsByClass("blog_list");
		for (Element element : bloglist) {
			CloumnModel item = new CloumnModel();
			
			String title = element.select("h1").text();
			System.out.println("cloumn title =="+ title);
			String link = element.select("h1").select("a").last().attr("href");
			Log.e("href=======", link);
			String content = element.getElementsByTag("p").text();
			String username = element.getElementsByClass("user_name").text();
			String date = element.getElementsByClass("time").text();
//			CloumnTag tag = null;
//			taglist = new ArrayList<CloumnTag>();
//			for (Element tagElement : element.getElementsByClass("tag")) {
//				tag = new CloumnTag();
//				String tagName = tagElement.text();
//				String tagUrl = tagElement.attr("href");
//				tag.setTagName(tagName);
//				tag.setTagLink(tagUrl);
//				taglist.add(tag);
//			}
			item.setLink(link);
			item.setTitle(title);
			item.setContent(content);
			item.setUsername(username);
			item.setDate(date);
			
			//item.setTagList(taglist);
			list.add(item);
		}
		map.put("cloumn", list);
		return map;

	}

	public static int getPageNo(String s) {
		Pattern p = Pattern.compile("[^0-9]");
		Matcher m = p.matcher(s);
		String path = m.replaceAll("").trim();
		return Integer.parseInt(path);
	}

	/**
	 * 半角转换为全角 全角---指一个字符占用两个标准字符位置。 半角---指一字符占用一个标准的字符位置。
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

}
